extends Node2D

var is_dying: bool = false
var death_progress: float = 0.0
var original_points: PackedVector2Array = []

# 支撑系统 - 时间控制版
@export var support_scene: PackedScene
var support_timer: float = 0.0
var support_interval: float = 1.5 # 每隔1秒生成一个
var all_supports: Array = []

# 游戏状态变量
var has_reached_end: bool = false

# === 蛇移动参数 ===
@onready var line: Line2D = $Line2D
@onready var timer: Timer = $Timer
@onready var charge_bar: ProgressBar = $ChargeBar  # 进度条节点

@export var goal: PackedScene

var x_increment: float = 20.0
var max_line_length: float = 800.0
var move_speed: float = 10.0
var smooth_factor: float = 0.8
var timer_interval: float = 0.02
var start_point: Vector2
var current_direction: float = 0.0

# === 光环系统参数 ===
var ring_radius: float = 0.0
var max_ring_radius: float = 0.0
var ring_speed: float = 1000.0
var ring_width: float = 8.0
var is_ring_active: bool = false

# === 充能系统参数 ===
var charge_value: float = 50.0
var max_charge: float = 50.0
var charge_regen_speed: float = 10.0
var ring_cost: float = 20.0
var can_use_ring: bool = false

# === 游戏状态 ===
var is_alive: bool = true
var screen_size: Vector2

func _ready():
	Translate.live = true
	timer.wait_time = timer_interval
	screen_size = get_viewport_rect().size
	
	# 计算能覆盖屏幕的光环最大半径
	max_ring_radius = max(screen_size.x, screen_size.y) * 0.8
	
	start_point = Vector2(-300, screen_size.y / 2)
	
	# 初始化进度条
	charge_bar.max_value = max_charge
	charge_bar.value = 50
	
	initialize_line()
	timer.timeout.connect(_on_timer_timeout)

func initialize_line():
	line.clear_points()
	var initial_points = 15
	for i in range(initial_points):
		var x_offset = i * 20.0
		var point = start_point + Vector2(x_offset, 0)
		line.add_point(point)

func _on_timer_timeout():
	if not is_alive:
		return
	
	if not has_reached_end:
		sync_end_point_speed()
	
	# --- 1. 蛇头移动逻辑 ---
	var mouse_pos = get_global_mouse_position()
	var last_point = line.get_point_position(line.get_point_count() - 1)
	
	var target_direction = atan2(mouse_pos.y - last_point.y, 500.0)
	current_direction = lerp_angle(current_direction, target_direction, smooth_factor)
	
	var new_point = last_point + Vector2(
		cos(current_direction) * x_increment,
		sin(current_direction) * x_increment
	)
	
	var max_x = start_point.x + max_line_length
	if new_point.x > max_x:
		new_point.x = max_x
		new_point.y = last_point.y + sin(current_direction) * x_increment * 2.0
	
	new_point.y = clamp(new_point.y, 125, 975)
	
	line.add_point(new_point)
	#move_points_left()
	light_smooth_line()
	# --- 蛇头移动结束 ---
	
	# --- 2. 充能系统 ---
	if not is_ring_active:
		charge_value = min(charge_value + charge_regen_speed * timer.wait_time, max_charge)
		charge_bar.value = charge_value
		can_use_ring = charge_value >= ring_cost
	
	# --- 3. 光环系统 ---
	if is_ring_active:
		ring_radius += ring_speed * timer.wait_time
		if ring_radius >= max_ring_radius:
			is_ring_active = false
			ring_radius = 0.0
		else:
			# 光环扩散过程中，检测并通知障碍物
			var ring_center = line.get_point_position(line.get_point_count() - 1)
			scan_obstacles_with_ring(ring_center, ring_radius)
	
	line.add_point(new_point)
	
	# --- 4. 死亡检测 ---
	check_death_collision()

func create_support_at(bridge_point: Vector2):
	if not support_scene:
		return
	
	var support = support_scene.instantiate()
	var compensated_position = bridge_point
	compensated_position.x -= move_speed * get_process_delta_time() * 60
	support.global_position = compensated_position
	
	# 动态计算所需长度：从桥的点到屏幕底部的距离
	var screen_bottom = get_viewport_rect().size.y
	var required_length = screen_bottom - bridge_point.y
	
	# 关键：调用新的setup方法，传入当前速度和计算的长度
	if support.has_method("setup"):
		support.setup(move_speed, required_length)
	
	add_child(support)
	all_supports.append(support)

func sync_end_point_speed():
	all_supports = all_supports.filter(func(s): return s != null and is_instance_valid(s))
	for support in all_supports:
		if support.has_method("update_speed"): # 调用新方法
			support.update_speed(move_speed)   # 立即更新
	
	var end_points = get_tree().get_nodes_in_group("end_point")
	for end_point in end_points:
		if end_point.has_method("set_move_speed"):
			end_point.set_move_speed(move_speed)

func move_points_left():
	for i in range(line.get_point_count()):
		var point_pos = line.get_point_position(i)
		point_pos.x -= move_speed
		line.set_point_position(i, point_pos)
	
	while line.get_point_count() > 0 and line.get_point_position(0).x < start_point.x - 50:
		line.remove_point(0)

func light_smooth_line():
	var points_count = line.get_point_count()
	if points_count < 3:
		return
	
	for i in range(1, points_count - 1):
		var prev_point = line.get_point_position(i - 1)
		var current_point = line.get_point_position(i)
		var next_point = line.get_point_position(i + 1)
		
		var smoothed_point = current_point * 0.9 + (prev_point + next_point) * 0.05
		line.set_point_position(i, smoothed_point)

func _process(delta):
	if Translate.h:
		line.default_color = Color("8787bb")
	else:
		line.default_color = Color("ffffff")
	
	if is_dying:
		update_death_animation(delta)
	
	if not is_alive:
		return
	
	sync_end_point_speed()
	
	for i in range(line.get_point_count()):
		var point_pos = line.get_point_position(i)
		point_pos.x -= move_speed * delta * 60
		line.set_point_position(i, point_pos)
	
	while line.get_point_count() > 0 and line.get_point_position(0).x < start_point.x - 50:
		line.remove_point(0)
	
	# 累积时间
	support_timer += delta
	
	# 每间隔2秒，在当前的桥头位置生成一个支撑
	if support_timer >= support_interval:
		if line.get_point_count() > 0:
			var current_head_pos = line.get_point_position(line.get_point_count() - 1)
			create_support_at(current_head_pos)
		support_timer = 0.0 # 重置计时器
	
	# 实时更新蛇头方向（更流畅）
	if line.get_point_count() > 0:
		var mouse_pos = get_global_mouse_position()
		var last_point = line.get_point_position(line.get_point_count() - 1)
		var target_direction = atan2(mouse_pos.y - last_point.y, 500.0)
		
		current_direction = lerp_angle(current_direction, target_direction, smooth_factor * 10 * delta)
	
	queue_redraw()

func _input(event):
	if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
		if is_alive and can_use_ring and not is_ring_active:
			activate_ring()

func activate_ring():
	is_ring_active = true
	ring_radius = 0.0
	charge_value = max(0, charge_value - ring_cost)
	charge_bar.value = charge_value
	can_use_ring = charge_value >= ring_cost

# === 核心修改：光环扫描与障碍物通知 ===
func scan_obstacles_with_ring(ring_center: Vector2, ring_radius: float):
	var obstacles = get_tree().get_nodes_in_group("obstacle")
	
	for obstacle in obstacles:
		# 确保障碍物是Area2D且有碰撞形状
		if not (obstacle is Area2D):
			continue
		
		var collision_shape = _get_obstacle_collision_shape(obstacle)
		if collision_shape == null:
			continue
		
		# 检查光环是否与障碍物相交
		if is_ring_intersecting_obstacle(ring_center, ring_radius, obstacle, collision_shape):
			# 如果相交，就通知障碍物显示轮廓
			if obstacle.has_method("on_scanned"):
				obstacle.on_scanned()
			# 可选：同步移动速度
			if obstacle.has_method("set_move_speed"):
				obstacle.set_move_speed(move_speed)

func _get_obstacle_collision_shape(obstacle: Area2D):
	# 尝试获取碰撞形状，支持CollisionPolygon2D或CollisionShape2D
	var polygon = obstacle.get_node_or_null("CollisionPolygon2D")
	if polygon:
		return polygon
	
	var shape = obstacle.get_node_or_null("CollisionShape2D")
	if shape:
		return shape
	
	return null

func is_ring_intersecting_obstacle(ring_center: Vector2, ring_radius: float, obstacle: Area2D, collision_node: Node) -> bool:
	# 获取障碍物全局边界（简单矩形近似，性能较好）
	var global_rect = _get_obstacle_global_rect(obstacle, collision_node)
	if global_rect == null:
		return false
	
	# 计算光环圆与障碍物矩形的相交（快速检测）
	var closest_x = clamp(ring_center.x, global_rect.position.x, global_rect.position.x + global_rect.size.x)
	var closest_y = clamp(ring_center.y, global_rect.position.y, global_rect.position.y + global_rect.size.y)
	
	var distance_x = ring_center.x - closest_x
	var distance_y = ring_center.y - closest_y
	
	return (distance_x * distance_x + distance_y * distance_y) <= (ring_radius * ring_radius)

func _get_obstacle_global_rect(obstacle: Area2D, collision_node: Node):
	# 根据碰撞节点类型计算全局边界矩形
	if collision_node is CollisionPolygon2D:
		var polygon = collision_node.polygon
		if polygon.size() == 0:
			return null
		
		# 计算多边形包围盒
		var min_point = polygon[0]
		var max_point = polygon[0]
		for point in polygon:
			min_point = min_point.min(point)
			max_point = max_point.max(point)
		
		var global_pos = obstacle.global_position + collision_node.position
		return Rect2(global_pos + min_point, max_point - min_point)
	
	elif collision_node is CollisionShape2D:
		var shape = collision_node.shape
		if shape is RectangleShape2D:
			var global_pos = obstacle.global_position + collision_node.position
			return Rect2(global_pos - shape.size * 0.5, shape.size)
		elif shape is CircleShape2D:
			var global_pos = obstacle.global_position + collision_node.position
			var diameter = Vector2(shape.radius * 2, shape.radius * 2)
			return Rect2(global_pos - Vector2(shape.radius, shape.radius), diameter)
	
	return null

func check_death_collision():
	if Translate.h:
		return
	
	if line.get_point_count() == 0 or not is_alive or has_reached_end:
		return
	
	var head_pos = line.get_point_position(line.get_point_count() - 1)
	
	# 1. 检测终点（优先检测）
	var end_points = get_tree().get_nodes_in_group("end_point")
	for end_point in end_points:
		# 确保终点有检测方法
		if end_point.has_method("is_point_inside"):
			if end_point.is_point_inside(head_pos) and is_alive:
				reach_end_point()
				return
	
	# 2. 检测障碍物（原有逻辑）
	var obstacles = get_tree().get_nodes_in_group("obstacle")
	for obstacle in obstacles:
		if not (obstacle is Area2D):
			continue
		
		var collision_shape = _get_obstacle_collision_shape(obstacle)
		if collision_shape == null:
			continue
		
		if is_point_in_obstacle(head_pos, obstacle, collision_shape):
			die()
			return

func reach_end_point():
	has_reached_end = true
	is_alive = false
	Translate.live = false
	
	# 停止游戏逻辑
	timer.stop()
	
	Translate.animated_grid()
	await Translate.animation_comlpeted
	get_tree().change_scene_to_packed(goal)
	

func is_point_in_obstacle(point: Vector2, obstacle: Area2D, collision_node: Node) -> bool:
	# 将检测点转换到障碍物的局部坐标
	var local_point = point - (obstacle.global_position + collision_node.position)
	
	if collision_node is CollisionPolygon2D:
		return _is_point_in_polygon(local_point, collision_node.polygon)
	elif collision_node is CollisionShape2D:
		var shape = collision_node.shape
		if shape is RectangleShape2D:
			var half_size = shape.size * 0.5
			return (abs(local_point.x) <= half_size.x and abs(local_point.y) <= half_size.y)
		elif shape is CircleShape2D:
			return local_point.length() <= shape.radius
	
	return false

func _is_point_in_polygon(point: Vector2, polygon: PackedVector2Array) -> bool:
	var inside = false
	var j = polygon.size() - 1
	
	for i in range(polygon.size()):
		if ((polygon[i].y > point.y) != (polygon[j].y > point.y)):
			var intersect_x = (polygon[j].x - polygon[i].x) * (point.y - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x
			if point.x < intersect_x:
				inside = !inside
		j = i
	
	return inside

func die():
	if is_dying:  # 防止重复触发
		return
	
	Translate.live = false
	is_alive = false
	is_dying = true
	
	# 停止游戏逻辑
	if timer:
		timer.stop()
	
	# 记录桥的初始位置
	original_points.clear()
	for i in range(line.get_point_count()):
		original_points.append(line.get_point_position(i))
	
	# 开始坠落动画
	death_progress = 0.0

func update_death_animation(delta):
	# 更新进度（1秒完成动画）
	death_progress += delta / 1.0
	
	if death_progress >= 4.0:
		Translate.cai += 1
		get_tree().reload_current_scene()
		return
		
	if get_tree().current_scene.name == "End_Game" and Translate.cai >= 6:
		$diedie2.modulate.a += 0.005
	else:
		$diedie.modulate.a += 0.005
	
	# 桥向下坠落（每帧向下移动5像素）
	for i in range(line.get_point_count()):
		var current_pos = line.get_point_position(i)
		line.set_point_position(i, current_pos + Vector2(0, 1))
	
	# 逐渐消失（1秒内从完全不透明到完全透明）
	line.modulate.a = 1.0 - death_progress

# === 绘制光环 ===
func _draw():
	if is_ring_active and line.get_point_count() > 0:
		var ring_center = line.get_point_position(line.get_point_count() - 1)
		
		if Translate.h:
			draw_arc(ring_center, ring_radius, 0, TAU, 128, Color("8787bb"), ring_width)
		else:
			draw_arc(ring_center, ring_radius, 0, TAU, 128, Color.WHITE, ring_width)
		
		# 内外发光效果
		draw_arc(ring_center, ring_radius - ring_width/2, 0, TAU, 128, Color(1, 1, 1, 0.3), ring_width/2)
		draw_arc(ring_center, ring_radius + ring_width/2, 0, TAU, 128, Color(1, 1, 1, 0.2), ring_width/2)
